package com.ibp.service.impl;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.ibp.entity.AppMgr;
import com.ibp.service.AppMgrService;
import com.ibp.service.DictDataService;
import com.ibp.service.FSHttpService;
import com.ibp.utils.PropertyUtils;
import com.ibp.utils.RegeUtils;
import com.ibp.utils.StringUtil;

@Service("appMgrServiceImpl")
public class AppMgrServiceImpl implements AppMgrService, InitializingBean {

	private static Logger logger = LoggerFactory
			.getLogger(AppMgrServiceImpl.class);

	@Autowired
	PropertyUtils propertyUtils;

	@Autowired
	FSHttpService fSHttpServiceImpl;

	
	private String ibms_ip = null;
	private String ibms_port = null;
	private String url = null;
	private String query_apps=null;
	private String add_app=null;
	private String delete_app=null;
	private String update_app=null;
	  @Autowired
	  DictDataService dictDataServiceImpl;
	  private ServletContext servletContext; 

		@Override
		public void afterPropertiesSet() throws Exception {
			this.servletContext = dictDataServiceImpl.getServletContext();
		  	logger.info("初始化服务节点ip和port配置,servletContext:"+servletContext); 
		    Map<String,Map<String,String>> dictMap = (Map<String, Map<String, String>>) this.servletContext.getAttribute("dictMap");
		    
		    this.ibms_ip = 	  dictMap.get("http.ibms").get("ip");
		    this.ibms_port =  dictMap.get("http.ibms").get("port");
		    this.url = ("http://" + this.ibms_ip + ":" + this.ibms_port + "/");
		    this.query_apps= dictMap.get("http.ibms").get("query.apps");
		    this.add_app= dictMap.get("http.ibms").get("add.app");
		    this.delete_app= dictMap.get("http.ibms").get("delete.app");
		    this.update_app= dictMap.get("http.ibms").get("update.app");
		}
	@Override
	public List<AppMgr> getAppMgrList(AppMgr filter) {
		List<AppMgr> apps = new ArrayList<AppMgr>();
		String response = this.fSHttpServiceImpl.sendPostRequest(this.url
				+ this.query_apps);
		if (!StringUtil.isEmpty(response)) {
			apps = parseResponse(response);
		}
		logger.debug("查询AppMgr结果：{}", apps);
		// 过滤掉不符合条件的记录
		apps = filter(apps, filter);
		logger.debug("过滤后的结果：{}", apps);
		return apps;
	}

	/***
	 * 过滤结果集
	 * 
	 * @param list
	 * @param srm
	 * @return
	 */
	public List<AppMgr> filter(List<AppMgr> apps, AppMgr filter) {
		// 入参检查
		if (filter == null
				|| (StringUtils.isBlank(filter.getApp())
						&& StringUtils.isBlank(filter.getDesc()) && StringUtils
							.isBlank(filter.getBin()))) {
			return apps;
		}

		List<AppMgr> result = new ArrayList<AppMgr>();
		// 遍历每条记录的内容，若匹配则记入result
		for (AppMgr entry : apps) {
			if (RegeUtils.match(entry.getApp(), filter.getApp())
					&& RegeUtils.match(entry.getDesc(), filter.getDesc())
					&& RegeUtils.match(entry.getBin(), filter.getBin())) {
				result.add(entry);
			}
		}

		return result;
	}

	protected List<AppMgr> parseResponse(String response) {
		// 检查入参
		if (StringUtils.isBlank(response)) {
			return null;
		}
		String[] respStr = response.split("\n");
		for (String ss : respStr) {
			logger.debug("每行记录：{}", ss);
		}

		// 存放处理结果
		List<AppMgr> list = new ArrayList<AppMgr>();

		for (int i = 0; i < respStr.length; ++i) {
			AppMgr app = new AppMgr();
			String[] s = respStr[i].split(" ");

			Boolean noServerNode = true;
			logger.debug("查询结果的记录中的列数：{}", s.length);
			if (7 == s.length) {
				noServerNode = false;
			}

			app.setApp(s[0]);
			app.setDesc(s[1]);
			app.setBin(s[2]);
			app.setTimeout(s[3]);
			app.setTimeout2(s[4]);
			if (noServerNode == true) {
				logger.debug("无效标记值：{}", s[5]);
				app.setInvalid(checkoutValid(s[5]));
			} else {
				app.setServer_node(s[6]);
				app.setInvalid(checkoutValid(s[5]));
			}
			list.add(app);
		}

		return list;

	}

	//有效标记字符转换
	private String checkoutValid(String invalid) {
		if (invalid.equals("0")) {
			return "有效";
		} else if (invalid.equals("1")) {
			return "无效";
		} else {
			return null;
		}
	}



	// 删除app
	@Override
	public void deleteApp(AppMgr appMgr) {
	
		String paramsJson = objToJson(appMgr);
		logger.debug("删除记录的主键json：{}", paramsJson);
		String response = this.fSHttpServiceImpl.sendPostRequest(this.url
				+ this.delete_app, paramsJson);
		if (!StringUtil.isEmpty(response)) {
			logger.debug("删除成功");
		}

	}

	// 修改app
	@Override
	public void updateApp(AppMgr appMgr) {
		
		String paramsJson = objToJson(appMgr);
		logger.debug("修改记录json：{}", paramsJson);
		String response = this.fSHttpServiceImpl.sendPostRequest(this.url
				+ this.update_app, paramsJson);
		if (!StringUtil.isEmpty(response)) {
			logger.debug("修改成功");
		}

	}

	// 增加app
	@Override
	public void addApp(AppMgr appMgr) {
		
		String paramsJson = objToJson(appMgr);
		logger.debug("增加记录json：{}", paramsJson);
		String response = this.fSHttpServiceImpl.sendPostRequest(this.url
				+ this.add_app, paramsJson);
		if (!StringUtil.isEmpty(response)) {
			logger.debug("增加成功");
		}
	}	

	public String objToJson(Object obj) {
		return JSON.toJSONString(obj);

	}

}
